package com.zjj.filmcommentapi.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.zjj.filmcommentapi.dao.UserMapper;
import com.zjj.filmcommentapi.model.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
@Component
public class AuthenticationUtil {
    @Autowired
    UserMapper userMapper;
    @Resource
    RedisUtil redisUtil;

    public Boolean fliterLogin(String token) {
        if (StringUtils.isBlank(token)) {
            return false;
        } else {
            // 获取token中的account
            String account;
            try {
                account = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
               return false;
            } catch (Exception e) {
                throw new RuntimeException("401");
            }
            List tokenList = redisUtil.getList(account, 0, -1);
            if (!tokenList.contains(token)) {
               return false;
            }
            // 验证token
            Boolean hasToken = redisUtil.hasKey(token);
            if (!hasToken) {
              return false;
            }
            Long expired = redisUtil.getTokenExpire(token);
            if (expired <= 0L) {
              return false;
            }
            User user = (User) redisUtil.sentinelGet(token);
            if (user == null) {
                return false;
            }
            // jwt验证 解密验证token
            try {
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                jwtVerifier.verify(token); // jwt= jwtVerifier.verify(token); jwt.getClaim("key").asString() 可以解析出数
                redisUtil.renewToken(token, user);
            } catch (JWTVerificationException E) {
                return false;
            }
        }
        return true;
    }
}
